package com.jd.finance.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日期处理工具类
 * @author 李庆博
 * 修改默认日期格式
 */
public class DateUtil {

    private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);

    public static final String DATE_PATTERN_SIMPLE = "yyyy-MM-dd HH:mm:ss";

    public static final String defaultDatePattern = "yyyy-MM-dd HH:mm:ss.SSS";

    public static final String defaultTimestampPattern = "yyyy-MM-dd HH:mm:ss.SSS";

    public static final String DATE_PATTERN = "yyyy-MM-dd";
    public static final String DATE_PATTERN_DAY = "yyyyMMdd";
    public static final String DATE_PATTERN_HOUR = "yyyyMMddHH";
    public static final String DATE_PATTERN_YYMMDD = "yyMMdd";
    public static final String DATE_PATTERN_SECOND = "yyyyMMddHHmmss";

    public static final String DATE_PATTERN_00 = "yyyy-MM-dd HH:mm:00";
    public static final String DATE_PATTERN_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String datePatternYYMMDD = "yyyyMMdd" ;
    public static final String datePatternHHmmss = "HHmmss" ;
    public static final String datePatternYY_MM_DD = "yyyy-MM-dd" ;
    public static final String datePatternYY_MM = "yyyy-MM" ;
    public static final String datePatternYY_MM_DDHHMMSS ="yyyy-MM-dd HH:mm:ss";
    public static final String datePatternYYMM ="yyyyMM";
    public static final String datePatternYYYYVMMVDD="yyyy/MM/dd";
    public static final String datePatternMMDDYYYY="MM/dd/yyyy";
    public static final String datePatternMMMDDYYYYHHMMSS = "MMM d yyyy HH:mm:ss";
    public static final String datePatternMMMDDYYYY = "MMM d yyyy";
    public static final String datePatternYYYY ="yyyy";//瀵瑰簲骞�
    public static String getTimeByCustomPattern(Date date, String pattern) {
        return new SimpleDateFormat(pattern).format(date);
    }
    public List ls=new ArrayList();

    /**
     * 得到系统当前时间 格式:yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static Date parse(String str) throws ParseException {
        return parse(str, defaultDatePattern);
    }
    public static String getTimeByPattern(Date date, String formatType) {
        return new SimpleDateFormat(formatType).format(date);
    }
    public static String getCurrentDateStr() {
        SimpleDateFormat df = new SimpleDateFormat(datePatternYY_MM_DD);
        return df.format(new Date());
    }

    public static String getDatePatternYY_MM_DD(String datePatternyyyyMMdd) {

        SimpleDateFormat dfold = new SimpleDateFormat(DATE_PATTERN_DAY);
        try {
            Date parseDate = dfold.parse(datePatternyyyyMMdd);
            SimpleDateFormat df = new SimpleDateFormat(datePatternYY_MM_DD);
            return df.format(parseDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date parse(String str, String pattern) {
        if (str == null) {
            return null;
        }
        try {
            return new SimpleDateFormat(pattern, Locale.US).parse(str);
        } catch (ParseException e) {
            throw new RuntimeException("Invalid Date String [" + str + "] in patter[" + pattern + "]");
        }
    }
    /**
     * 得到系统当前时间 参数为格式化字符串 如：yyyy-MM-dd HH:mm:ss
     * @param formatStr
     * @return
     */
    public static String getCurrentDateStr(String formatStr) {
        SimpleDateFormat df = new SimpleDateFormat(formatStr);
        return df.format(new Date());
    }

    /**
     * 转换非法字符，目前是把单引号转成双引号
     * @param parm
     * @return
     */
    public static String conversionInvalid(String parm){
        return parm.replaceAll("'","''");
    }
    /**
     * 校验日期是否正确
     * @param date
     * @return
     */
    public static boolean validateDate(String date){
        String datePattern1 = "\\d{4}-\\d{2}-\\d{2}";
        String datePattern2 = "^((\\d{2}(([02468][048])|([13579][26]))"
                + "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|"
                + "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"
                + "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?("
                + "(((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?"
                + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
        if ((date != null)) {
            Pattern pattern = Pattern.compile(datePattern1);
            Matcher match = pattern.matcher(date);
            if (match.matches()) {
                pattern = Pattern.compile(datePattern2);
                match = pattern.matcher(date);
                return match.matches();
            }
            else {
                return false;
            }
        }
        return false;
    }

    /**
     * 按照客户端日期格式转化日期，如：2005-11-07T16:21:27.123
     * @param dateObj	Object	日期对象
     * @return			String
     * @version 0.1/2005-11-7
     */
    public static String dateFormatForClient(Object dateObj){
        String date = dateFormat(dateObj,defaultTimestampPattern);
        return date == null ? null : date.replace(' ','T');
    }
    /**
     * 将日期对象格式化成字符串
     * @param    dateObj     日期对象 Date/Calendar
     * @return   String      格式化的日期表示
     */
    public static String dateFormat(Object dateObj) {
        return dateFormat(dateObj,null);
    }

    /**
     * 将日期对象格式化
     * @param    dateObj     日期对象 Date/Calendar
     * @param    pattern     日期和时间的表示格式
     * @return   String      格式化的日期表示
     */
    public static String dateFormat(Object dateObj, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(
                (pattern == null) ? defaultDatePattern : pattern,
                Locale.CHINA);
        if( dateObj == null ){
            return null;
        }
        else if (dateObj instanceof Calendar) { //Calendar
            Date date = ((Calendar) dateObj).getTime();
            return sdf.format(date);
        }else if (dateObj instanceof java.sql.Date){
            Date date = new Date(((java.sql.Date)dateObj).getTime());
            return sdf.format(date);
        }else if (dateObj instanceof java.sql.Time){
            Date date = new Date(((java.sql.Time)dateObj).getTime());
            return sdf.format(date);
        }else if (dateObj instanceof Timestamp){
            Date date = new Date(((Timestamp)dateObj).getTime());
            sdf = new SimpleDateFormat((pattern == null) ? defaultTimestampPattern : pattern,Locale.CHINA);
            return sdf.format(date);
        }else if (dateObj instanceof Date) { //date
            return sdf.format((Date) dateObj);
        } else {
            return null;
        }
    }

    /**
     * 根据输入的日期字符串按照默认日期格式（yyyy-MM-dd HH:mm:ss.SSS），构造日期对象（Date）并返回
     * @param dateStr	String	日期字符串，如：2005-01-01 12:00:00.000
     * @return			Date
     */
    public static Date toDate(String dateStr){
        return toDate(dateStr,null);
    }

    /**
     * 根据输入的日期字符串构造日期对象，并返回
     * @param dateStr	String	日期字符串，如：2005-01-01 12:00:00.000
     * @param pattern	String	日期格式
     * @return			Date
     */
    public static Date toDate(String dateStr,String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(
                (pattern == null) ? defaultDatePattern : pattern,Locale.CHINA);
        Date dateReturn = null;
        try {
            dateReturn = sdf.parse(dateStr);
        } catch (ParseException e) {
            System.out.println("unknown date format:" + dateStr);
        }
        return dateReturn;
    }

    /**
     * 根据输入的日期字符串按照默认日期格式（yyyy-MM-dd HH:mm:ss），构造日历对象（Calendar）并返回
     * @param dateStr	String	日期字符串，如：2005-01-01 12:00:00.000
     * @return			Calendar
     */
    public static Calendar toCalendar(String dateStr){
        return toCalendar(dateStr,null);
    }

    /**
     * 根据输入的日期字符串构造日历对象（Calendar）并返回
     * @param dateStr	String	日期字符串，如：2005-01-01 12:00:00.000
     * @param pattern	String	日期格式
     * @return
     */
    public static Calendar toCalendar(String dateStr,String pattern){
        Date date = toDate(dateStr,pattern);
        Calendar calendarReturn = Calendar.getInstance();
        calendarReturn.setTime(date);
        return calendarReturn;
    }
    /**
     * 将时间戳转化成ORACLE的日期格式
     * @param 	timestamp		String 日期字符串 		2005-01-01 12:10:11.123
     * @return					String ORACLE格式日期	TO_TIMESTAMP('2005-01-01 12:10:11.123','yyyy-mm-dd hh24:mi:ssxff')
     * @version 0.2/2005-12-20
     */
    public static String formatTimestamp(String timestamp){
        if( timestamp == null ) {
            return null;
        } else if( timestamp.indexOf('.') > 0 ){ //timestamp
            return "TO_TIMESTAMP('" + timestamp + "','yyyy-mm-dd hh24:mi:ssxff')";
        }
        else //date
        {
            return "TO_DATE('" + timestamp + "','yyyy-mm-dd hh24:mi:ss')";
        }
    }

    /**
     * 将日期转化成ORACLE的日期格式
     * @param date	String 2005-01-01
     * @return		String TO_DATE('2005-01-01','yyyy-mm-dd')
     */
    public static String formatDate(String date){
        if( date == null ) {
            return null;
        }
        StringBuffer result = new StringBuffer();
        result.append("TO_DATE('");
        int indexFirstSpace = date.indexOf(' ');
        if( indexFirstSpace > 0 ){
            result.append(date.substring(0,indexFirstSpace));
        }
        else{
            result.append(date);
        }
        result.append("','yyyy-mm-dd')");
        return result.toString();
    }

    /**
     * 将日期时间转化成ORACLE的日期格式
     * @param dateTime	String	2005-01-01 12:10:11
     * @return			String	TO_DATE('2005-01-01 12:10:11','yyyy-mm-dd hh24:mi:ss')
     */
    public static String formatDatetime(String dateTime){
        if( dateTime == null ) {
            return null;
        }

        StringBuffer result = new StringBuffer();
        result.append("TO_DATE('");
        int indexFirstSpot = dateTime.indexOf('.');
        if( indexFirstSpot > 0 ){
            result.append(dateTime.substring(0,indexFirstSpot));
        }
        else{
            result.append(dateTime);
        }
        result.append("','yyyy-mm-dd hh24:mi:ss')");
        return result.toString();
    }

    /**
     * 计算两个日期之间相差的天数
     * if date1 > date2 返回正数
     * else if date1  < date2 返回负数
     * else 返回 0
     * @param date1	java.util.Date
     * @param date2 java.util.Date
     * @return		int
     */
    public static int diffDate(Date date1, Date date2) {
        GregorianCalendar gc1 = new GregorianCalendar();
        GregorianCalendar gc2 = new GregorianCalendar();
        gc1.setTime(date1);
        gc2.setTime(date2);
        return getDays(gc1, gc2);
    }

    public static int getDays(GregorianCalendar g1, GregorianCalendar g2) {
        int elapsed = 0;
        GregorianCalendar gc1, gc2;

        if (g2.after(g1)) {
            gc2 = (GregorianCalendar) g2.clone();
            gc1 = (GregorianCalendar) g1.clone();
        } else {
            gc2 = (GregorianCalendar) g1.clone();
            gc1 = (GregorianCalendar) g2.clone();
        }

        gc1.clear(Calendar.MILLISECOND);
        gc1.clear(Calendar.SECOND);
        gc1.clear(Calendar.MINUTE);
        gc1.clear(Calendar.HOUR_OF_DAY);
        gc1.clear(Calendar.HOUR);

        gc2.clear(Calendar.MILLISECOND);
        gc2.clear(Calendar.SECOND);
        gc2.clear(Calendar.MINUTE);
        gc2.clear(Calendar.HOUR_OF_DAY);
        gc2.clear(Calendar.HOUR);

        while (gc1.before(gc2)) {
            gc1.add(Calendar.DATE, 1);
            elapsed++;
        }

        return g1.after(g2) ? elapsed : -elapsed;
    }
    //	取得当前日期
    public static Date getCurrentDate()
    {
        return new java.sql.Date(new Date().getTime());
    }
    //把当前默认日期转化为字符串，toString(date,"yyyy-MM-dd");
    public static String toString(Date date, String format)
    {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(date);
    }

    /**
     * 时间格式加一个月
     * @param StringTime
     * @return
     */
    public static String DataFormatUtil(String StringTime){

        //String date1 = "2007-01";
        Date d2=null;
        DateFormat df = new SimpleDateFormat("yyyy-MM");
        try {
            Date d1 = df.parse(StringTime);
            Calendar  g = Calendar.getInstance();
            g.setTime(d1);
            g.add(Calendar.MONTH,+1);
            d2 = g.getTime();
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return df.format(d2);
    }
    /**
     * 时间格式减一个月
     * @param StringTime
     * @return
     */
    public static String MonthSubOne(String StringTime){

        //String date1 = "2007-01";
        Date d2=null;
        DateFormat df = new SimpleDateFormat("yyyy-MM");
        try {
            Date d1 = df.parse(StringTime);
            Calendar  g = Calendar.getInstance();
            g.setTime(d1);
            g.add(Calendar.MONTH,-1);
            d2 = g.getTime();
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return df.format(d2);
    }




    public static String MonthsSubCount(String startTime,String endTime) {
        if(startTime.split("-").length<=2) {
            startTime=startTime+"-00";
        }
        if(endTime.split("-").length<=2) {
            endTime=endTime+"-00";
        }
        SimpleDateFormat  format  =  new SimpleDateFormat("yyyy-MM-dd");
        Calendar   a2   =   Calendar.getInstance();
        Calendar   b2   =   Calendar.getInstance();
        try {
            a2.setTime(format.parse(startTime));
            b2.setTime(format.parse(endTime));
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        int result  = (b2.get(Calendar.YEAR)-a2.get(Calendar.YEAR))* 12
                +(b2.get(Calendar.MONTH)-a2.get(Calendar.MONTH));
        return String.valueOf(result+1);
    }

    /**
     * 取得两个日期之间的天数
     * @param startTime
     * @param endTime
     * @return
     */
    public static Long DaysSubCount(String startTime,String endTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTimePar;
        Date endTimePar;
        Long days=new Long(0);
        try {
            startTimePar= df.parse(startTime+" 00:00:00");
            endTimePar =df.parse(endTime+" 00:00:00");
            long l=endTimePar.getTime()-startTimePar.getTime();
            days=l/(24*60*60*1000);

        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return days;
    }

    /**
     * 取得两个日期之间的小时
     * @param startTime
     * @param endTime
     * @return
     */
    public static Long HoursSubCount(String startTime,String endTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTimePar;
        Date endTimePar;
        Long hours=new Long(0);
        try {
            startTimePar= df.parse(startTime);
            endTimePar =df.parse(endTime);
            long l=endTimePar.getTime()-startTimePar.getTime();
            hours=l/(60*60*1000);

        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return hours;
    }
    /**
     * 取得两个日期之间的小时
     * @param start
     * @param end
     * @return
     */
    public static BigDecimal HoursSubCount4BigDecimal(Date start,Date end) {

        BigDecimal startTime = new BigDecimal(start.getTime());
        BigDecimal endTime = new BigDecimal(end.getTime());
        BigDecimal result = new BigDecimal(0);
        try {
            result = endTime.subtract(startTime).divide(new BigDecimal(60*60*1000),2,BigDecimal.ROUND_HALF_UP);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 取得两个日期之间的小时-开始减去结束时间
     * @param start
     * @param end
     * @return
     */
    public static BigDecimal HoursSubCount4StartSubEnd(Date start,Date end) {


        return HoursSubCount4BigDecimal(end,start);
    }

    /**
     * 取得两个日期之间的天数
     * @param startTime
     * @param endTime
     * @return double
     */
    public static double daysSubCount1(String startTime,String endTime) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTimePar;
        Date endTimePar;
        double days=0.00;
        try {
            startTimePar= df.parse(startTime);
            endTimePar =df.parse(endTime);
            double l=endTimePar.getTime()-startTimePar.getTime();
            days=l/(24*60*60*1000);
            BigDecimal   b   =   new   BigDecimal(days);

            days = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return days;
    }

    /**
     * 返回当前日期的字符串
     * @return
     */
    public static String FormatToDay(String formatString ){
        //yyyy-MM-dd hh:mm:ss

        // yyyy-MM-dd
        Date date=new Date();
        SimpleDateFormat df=new SimpleDateFormat(formatString);
        String time=df.format(date);
        return time;
    }
    /**
     * 月份+1
     * @param StringTime
     * @return
     */
    public static String AddMonthByIndex(String StringTime,int index){

        //String date1 = "2007-01";
        Date d2=null;
        if(index <=0){
            return StringTime;
        }else{
            DateFormat df = new SimpleDateFormat("yyyy-MM");
            try {
                Date d1 = df.parse(StringTime);
                Calendar  g = Calendar.getInstance();
                g.setTime(d1);
                g.add(Calendar.MONTH,+index);
                d2 = g.getTime();
            } catch (ParseException e) {
                logger.error(e.getMessage(), e);
            }
            return df.format(d2);
        }

    }


    public static String getYearMonth(String str) {
        if (!StringUtils.isBlank(str)) {
            String[] array = str.split("-");
            String year = "";
            String month = "";
            if (array != null && array.length > 1) {
                month = String.valueOf(Integer.parseInt(array[1])
                        + Integer.parseInt("1"));
                if (Integer.parseInt(month) > 12) {
                    month = String.valueOf(Integer.parseInt(month) % 12);
                }
                if (Integer.parseInt(month) < 10) {
                    month = "0" + month;
                }
                if (Integer.parseInt(array[1]) == 12) {
                    year = String.valueOf((Integer.parseInt(array[0]) + Integer
                            .parseInt("1")));
                } else {
                    year = array[0];
                }
                str = year + "-" + month;
            }
        }
        return str;
    }
    //取得当前日期 时分秒
    public static Date getCurrentDateTime()
    {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
//		  System.out.println(dateString);
        ParsePosition pos = new ParsePosition(0);

        Date currentTime_2 = formatter.parse(dateString, pos);
        return currentTime_2;
    }
    /**
     * 取得当前月份的第一天和最后一天的字符串值 format YYYY-MM-DD
     * @return
     */
    public static String getFirstDayOfMonth(int index){
        Calendar cal = Calendar.getInstance();
        // 当前月＋1，即下个月
        cal.add(Calendar.MONTH, 1);
        // 将下个月1号作为日期初始zhii
        cal.set(Calendar.DATE, 1);
        // 下个月1号减去一天，即得到当前月最后一天
        cal.add(Calendar.DATE, -1);
        SimpleDateFormat df = new SimpleDateFormat(
                "yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH,index);
        c.set(Calendar.DATE, 1);
        return df.format(c.getTime());
    }

    /**
     * 基站租赁合同日期差计算月份
     * @param startTime
     * @param endTime
     * @return
     */
    public static int ContractMonthCount(String startTime,String endTime) {
        int yearsCount = 0;
        int monthsCount = 0;
        int daysCount = 0 ;

        String [] start = startTime.split("-");
        String [] end = endTime.split("-");
        //比较年份

        yearsCount = (Integer.parseInt(end[0]) - Integer.parseInt(start[0]))*12;

        //比较月份

        monthsCount = Integer.parseInt(end[1]) - Integer.parseInt(start[1]);


        //比较天数

        daysCount = Integer.parseInt(end[2]) - Integer.parseInt(start[2]);
        if(daysCount>15){
            daysCount =1;
        }else if(daysCount<-15){
            daysCount=-1;
        }else{
            daysCount=0;
        }
        return yearsCount+monthsCount+daysCount;
    }

    /**
     * 时间格式加2个小时
     * @param StringTime
     * @return
     */
    public static String HourSubOne(Date StringTime,int hour){

        //String date1 = "2007-01";
        Date d2=null;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        try {
//            Date d1 = df.parse(StringTime);
            Calendar  g = Calendar.getInstance();
            g.setTime(StringTime);
            g.add(Calendar.HOUR,+hour);
            d2 = g.getTime();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return df.format(d2);
    }


    public static int compareDate(String DATE1, String DATE2) {


        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
//                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
//                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            logger.error(exception.getMessage(), exception);
        }
        return 0;
    }
    public static String getSysDate(){
        String sysDate = DateUtil.toString(DateUtil.getCurrentDate(), "yyyy-MM-dd HH:mm:ss");
        return sysDate;
    }

    /**
     * 取得在指定时间上加减days天后的时间
     *
     * @param date
     *            指定的时间
     * @param days
     *            天数,正为加，负为减
     * @return 在指定时间上加减days天后的时间
     */
    public static Date addDays(Date date, int days) {
        Date time = null;
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.DAY_OF_MONTH, days);
        time = cal.getTime();
        return time;
    }

    public static Date addMin(Date date, int minutes) {
        Date time = null;
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.MINUTE, minutes);
        time = cal.getTime();
        return time;
    }

    public static Timestamp getCurrentTimeStamp(){
        Timestamp now = new Timestamp(System.currentTimeMillis());
        return now;
    }

    public static String dateToString(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(date);
    }

    public static String dateToYMString(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        return df.format(date);
    }

    public static int getIntervalMinutes(Date sDate, Date eDate) {

        if (null == sDate || null == eDate) {
            return 0;
        }

        long intervalMilli = eDate.getTime() - sDate.getTime();
        return (int) (intervalMilli / (60 * 1000));
    }

    public static long getIntervalSeconds(Date sDate, Date eDate) {

        if (null == sDate || null == eDate) {
            return 0;
        }

        long intervalMilli = eDate.getTime() - sDate.getTime();
        return (int) (intervalMilli / (1000));
    }

    public static int getIntervalHours(Date sDate, Date eDate) {

        if (null == sDate || null == eDate) {
            return 0;
        }

        long intervalMilli = eDate.getTime() - sDate.getTime();
        return (int) (intervalMilli / (60 * 1000 * 60));
    }


    /**
     * 计算2个日期之间相差的  相差多少年月日
     * 比如：2011-02-02 到  2017-03-02 相差 6年，1个月，0天
     * @param fromDate
     * @param toDate
     * @return
     */
//    public static DayCompare dayComparePrecise(Date fromDate, Date toDate){
//        Calendar  from  =  Calendar.getInstance();
//        from.setTime(fromDate);
//        Calendar  to  =  Calendar.getInstance();
//        to.setTime(toDate);
//        DayCompare dayCompare = new DayCompare();
//        int fromYear = from.get(Calendar.YEAR);
//        int fromMonth = from.get(Calendar.MONTH);
//        int fromDay = from.get(Calendar.DAY_OF_MONTH);
//        int toYear = to.get(Calendar.YEAR);
//        int toMonth = to.get(Calendar.MONTH);
//        int toDay = to.get(Calendar.DAY_OF_MONTH);
//        int year = toYear  -  fromYear;
//        int month = toMonth  - fromMonth;
//        int day = toDay  - fromDay;
//        dayCompare.setYear(year);
//        dayCompare.setMonth(month);
//        dayCompare.setDay(day);
//        return dayCompare;
//    }



    /**
     * 将XMLGregorianCalendar转换为Date
     * @param cal
     * @return
     */
    public static Date xmlDate2Date(XMLGregorianCalendar cal){
        return cal.toGregorianCalendar().getTime();
    }

    public static String xmlDate2DateByCustomPattern(XMLGregorianCalendar cal, String datePattern) {
        return dateFormat(xmlDate2Date(cal),datePattern);
    }

    /**
     * 将Date类转换为XMLGregorianCalendar
     * @param date
     * @return
     */
    public static XMLGregorianCalendar dateToXmlDate(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        DatatypeFactory dtf = null;
        try {
            dtf = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
        }
        XMLGregorianCalendar dateType = dtf.newXMLGregorianCalendar();
        dateType.setYear(cal.get(Calendar.YEAR));
        //由于Calendar.MONTH取值范围为0~11,需要加1
        dateType.setMonth(cal.get(Calendar.MONTH)+1);
        dateType.setDay(cal.get(Calendar.DAY_OF_MONTH));
        dateType.setHour(cal.get(Calendar.HOUR_OF_DAY));
        dateType.setMinute(cal.get(Calendar.MINUTE));
        dateType.setSecond(cal.get(Calendar.SECOND));
        return dateType;
    }
    public static void main(String[] args) throws Exception{
//		System.out.println(DaysSubCount("2019-05-06 08:32:00","2019-04-24 20:00:00"));
//		System.out.println( DateUtil.getDateField(toDate("2019-04-24 20:00:00.000"),Calendar.HOUR_OF_DAY));
        System.out.println(toString(getDateOnly(toDate("2019-04-24 20:00:00.000")),DATE_PATTERN_SIMPLE));
    }

    /**
     * 获取时间的元素，比如天、时、分、秒
     */
    public static int getDateField(Date date,int field){
        Calendar  calendar  =  Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(field);
    }

    /**
     * 带时分秒的日期格式改为无时分秒的日期格式
     * @param date
     * @return
     */
    public static Date getDateOnly(Date date) {
        String onlyDateStr= DateUtil.dateToString(date);//普通日期转yyyy-mm-dd
        return DateUtil.toDate(onlyDateStr,DateUtil.DATE_PATTERN);
    }
    public static String returnDateFormatToString(Date date ,String format){
        SimpleDateFormat creatFormatter = new SimpleDateFormat(format);
        return creatFormatter.format(date);
    }

    /**
     * 获取某天的开始时间
     *
     * @param datestr 日期 {@link Calendar}
     * @return {@link Calendar}
     */
//	public static Calendar beginOfDay(Calendar calendar) {
//		return calendar( truncate(calendar.getTime(), Calendar.DAY_OF_MONTH) );
//	}

    public static String beginOfDay(String datestr) throws ParseException {
        Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datestr);
        Calendar dateStart = Calendar.getInstance();
        dateStart.setTime(date);
        dateStart.set(Calendar.HOUR_OF_DAY, 0);
        dateStart.set(Calendar.MINUTE, 0);
        dateStart.set(Calendar.SECOND, 0);
        return  new SimpleDateFormat("yyyy-mm-dd hh24:mi:ss").format(dateStart.getTime());
    }

    /**
     * 获取某天的结束时间
     *
     * @return {@link Calendar}
     */
    public static String endOfDay(String datestr) throws ParseException {
        Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datestr);
        Calendar dateStart = Calendar.getInstance();
        dateStart.setTime(date);
        dateStart.set(Calendar.HOUR_OF_DAY, 23);
        dateStart.set(Calendar.MINUTE, 59);
        dateStart.set(Calendar.SECOND, 59);
        return  new SimpleDateFormat("yyyy-mm-dd hh24:mi:ss").format(dateStart.getTime());
    }
    public static Calendar calendar(Date date) {

        return calendar(date.getTime());

    }
    /**
     * 转换为Calendar对象
     *
     * @param millis 时间戳
     * @return Calendar对象
     */
    public static Calendar calendar(long millis) {
        final Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(millis);
        return cal;
    }


}
